﻿using log4net;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.OpenApi.Models;
using suirui.ZhuMu.Common;
using suirui.ZhuMu.Middlewares;
using suirui.ZhuMu.WebCore;
using Swashbuckle.AspNetCore.Filters;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using static suirui.ZhuMu.Framework.CustomApiVersion;

namespace suirui.ZhuMu.Framework
{
    /// <summary>
    /// Swagger 启动服务
    /// </summary>
    public static class SwaggerSetup
    {

        private static readonly ILog log = LogManager.GetLogger(typeof(GlobalExceptionMildd));

        public static void AddSwaggerSetup(this IServiceCollection services)
        {
            if (services == null) throw new ArgumentNullException(nameof(services));

            var basePath = AppContext.BaseDirectory;
            //var basePath2 = Microsoft.DotNet.PlatformAbstractions.ApplicationEnvironment.ApplicationBasePath;
            var ApiName = Appsettings.app(new string[] { "Startup", "ApiName" });

            #region 旧版本
            /*
            services.AddSwaggerGen(options =>
            {
                options.SwaggerDoc("v1", new Microsoft.OpenApi.Models.OpenApiInfo
                {
                    Version = "v1",
                    Title = "Zhumu Room API",
                    Description = "基础框架--云视讯 后台服务",
                });
                options.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme()
                {
                    Description = "在下框中输入请求头中需要添加Jwt授权Token：Bearer Token",
                    Name = "Authorization",
                    In = ParameterLocation.Header,
                    Type = SecuritySchemeType.ApiKey,
                    BearerFormat = "JWT",
                    Scheme = "Bearer"
                });

                options.AddSecurityRequirement(new OpenApiSecurityRequirement
                {
                    {
                        new OpenApiSecurityScheme
                        {
                            Reference = new OpenApiReference {
                                Type = ReferenceType.SecurityScheme,
                                Id = "Bearer"
                            }
                        },
                        new string[] { }
                    }
                });
                options.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, "", "suirui.ZhuMu.Room.xml"));
                options.DocumentFilter<HiddenApiFilter>();
                //options.OperationFilter<AddRequiredHeaderParameter>();                
            });*/
            #endregion

            
            services.AddSwaggerGen(c =>
            {
                //动态API在swagger中显示
                c.DocInclusionPredicate((docName, description) => true);
                //遍历出全部的版本，做文档信息展示
                typeof(ApiVersions).GetEnumNames().ToList().ForEach(version =>
                {
                    c.SwaggerDoc(version, new OpenApiInfo
                    {
                        Version = version,
                        Title = $"{ApiName} 接口文档——{RuntimeInformation.FrameworkDescription}",
                        Description = $"{ApiName} HTTP API " + version,
                        //Contact = new OpenApiContact { Name = ApiName, Email = "123@xxx.com", Url = new Uri("https://www.baidu.com/") },
                        //License = new OpenApiLicense { Name = ApiName + " 官方文档", Url = new Uri("https://www.baidu.com/") }
                    });
                    //c.OrderActionsBy(o => o.RelativePath);
                });


                try
                {
                    //这个就是刚刚配置的xml文件名
                    c.IncludeXmlComments(Path.Combine(basePath, "xml", "suirui.ZhuMu.MJGames.xml"));
                    c.IncludeXmlComments(Path.Combine(basePath, "xml", "suirui.ZhuMu.Entity.xml"));
                    c.IncludeXmlComments(Path.Combine(basePath, "xml", "suirui.ZhuMu.Model.xml"));
                }
                catch (Exception ex)
                {
                    log.Error("suirui.ZhuMu.MJGames.xml丢失，请检查并拷贝。\n" + ex.Message);
                }

                // 开启加权小锁
                c.OperationFilter<AddResponseHeadersFilter>();
                c.OperationFilter<AppendAuthorizeToSummaryOperationFilter>();

                // 在header中添加token，传递到后台
                c.OperationFilter<SecurityRequirementsOperationFilter>();
                c.DocumentFilter<HiddenApiFilter>();
                //c.OperationFilter<AddRequiredHeaderParameter>();

                // ids4和jwt切换
                //if (Permissions.IsUseIds4)
                if (false)
                {
                    //接入identityserver4
                    c.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme
                    {
                        Type = SecuritySchemeType.OAuth2,
                        Flows = new OpenApiOAuthFlows
                        {
                            Implicit = new OpenApiOAuthFlow
                            {
                                AuthorizationUrl = new Uri($"{Appsettings.app(new string[] { "Startup", "IdentityServer4", "AuthorizationUrl" })}/connect/authorize"),
                                Scopes = new Dictionary<string, string> {
                                {
                                    "blog.core.api","ApiResource id"
                                }
                            }
                            }
                        }
                    });
                }
                else
                {
                    // Jwt Bearer 认证，必须是 oauth2
                    c.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme
                    {
                        Description = "JWT授权(数据将在请求头中进行传输) 直接在下框中输入Bearer {token}（注意两者之间是一个空格）\"",
                        Name = "Authorization",//jwt默认的参数名称
                        In = ParameterLocation.Header,//jwt默认存放Authorization信息的位置(请求头中)
                        Type = SecuritySchemeType.ApiKey,
                        BearerFormat = "JWT",
                        Scheme = "Bearer"
                    });
                }
                c.AddSecurityRequirement(new OpenApiSecurityRequirement
                {
                    {
                        new OpenApiSecurityScheme
                        {
                            Reference = new OpenApiReference {
                                Type = ReferenceType.SecurityScheme,
                                Id = "Bearer"
                            }
                        },
                        new string[] { }
                    }
                });
            });
        }
    }
}
